<?php
namespace Tools\Controller;
use Common\Controller\AdminbaseController;

/**
 * 下载文件后台
 */
class AdminDownloadController extends AdminbaseController{


	protected $download_model;

	public function _initialize() {
		parent::_initialize();
		$this->table_model = D("ToolsDownload");
	}


	// 下载列表
	public function index(){

		//条件-名称
		$download_name = I('download_name');
		if($download_name){
			$where['download_name'] = array('like',"%$download_name%");
		}

		//数量
		$count=$this->table_model->where($where)->count();

		//分页
		$page = $this->page($count, 10);

		//列表
		$db_prefix=C('DB_PREFIX');
		$lists = $this->table_model
			-> where($where)
			-> order('orderby asc')
			-> limit($page->firstRow, $page->listRows)
			-> select();

		$this -> assign("page", $page->show('Admin'));
		$this -> assign('lists',$lists);
		$this -> display('index');
	}

	//填加
	public function add() {
		$this -> _modify();
	}


	//修改
	public function edit() {
		$this -> _modify();
	}




	private function _modify() {

		$form_id = I('download_id');
		$where['download_id'] = $form_id;

		if (IS_POST) {

			$result = array('status' => TRUE, 'info' => '', 'url' => '');

			if ($this->table_model ->create()) {
				if (!$form_id) {
					$insert_id = $this->table_model -> add();
					if ($insert_id) {
						$result['info'] = '添加成功';
					} else {
						$result['status'] = FALSE;
						$result['info'] = '添加失败';
					}
				} else {
					if($this->table_model -> where() -> save()) {
						$result['info'] = '保存成功';
					} else {
						$result['status'] = FALSE;
						$result['info'] = '保存失败';
					}
				}
			} else {
				//返回错误提示
				$result['status'] = FALSE;
				$result['info'] = $this->table_model -> getError();
			}

			if ($result['status']) {
				$this -> success($result['info'],U('AdminDownload/index'));
			} else {
				$this -> error($result['info']);
			}
		}

		//修改取单个值 form
		$form = $form_id ? $this->table_model -> find($form_id) : array();
		$this -> assign('download', $form);

		//模板
		$this -> display('AdminDownload/form');
	}



	//删除
	public function delete() {
		$download_id = I('download_id');
		$result = $this->table_model-> delete($download_id);
		$data = array(
			'status' => $result ? true : false,
			'info' => $result ? '' : '删除失败，ID：'.$download_id,
			'url' => '',
		);
		$this -> ajaxReturn($data);
	}

	/**
	 * 批量操作
	 * @param string 	处理类型 order排序,delete删除
	 */
	public function indexBat($type='order') {
		//排序
		if ($type == 'order') {
			$order_array = I('post.orderby');
			if ($this->table_model->saveBatch($order_array, 'download_id', 'orderby') !== FALSE) {
				$this -> success('排序成功');
			} else {
				$this -> error('排序出错');
			}
		}
		if ($type == 'delete') {
			$ids = I('post.ids');
			if ($this->table_model -> delete(implode(',',$ids)) !== FALSE) {
				$this -> success('删除成功');
			} else {
				$this -> error('删除失败');
			}
		}
	}


}